<template>
  <div class="role">
    <pageSearch
      :searchConfig="searchConfig"
      @queryClick="handleQueryClick"
      @resetClick="handleResetClick"
    />
    <pageContent
      :contentConfig="contentConfig"
      ref="contentRef"
      @newBtnClick="handleNewClick"
      @editBtnClick="handleEditClick"
    />
    <pageModal :modalConfig="modalConfig" :otherInfo="otherInfo" ref="modalRef">
      <template #menuList>
        <el-tree
          ref="treeRef"
          :data="entireMenus"
          show-checkbox
          highlight-current
          node-key="id"
          :props="{ children: 'children', label: 'name' }"
          @check="handleElTreeCheck"
        />
      </template>
    </pageModal>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue'
// 搜索框
import pageSearch from '@/components/page-search/page-search.vue'
import searchConfig from './config/search.config'
// 主体表格
import pageContent from '@/components/page-content/page-content.vue'
import contentConfig from './config/content.config'
// 弹出框
import pageModal from '@/components/page-modal/page-modal.vue'
import modalConfig from './config/modal.config'

import usePageModal from '@/hooks/usePageModal'
import usePageContent from '@/hooks/usePageContent'
import useMainStore from '@/store/main/main'
import { storeToRefs } from 'pinia'
import { mapMenuListToIds } from '@/utils/map-menus'

const { contentRef, handleQueryClick, handleResetClick } = usePageContent()
// const { modalRef, handleNewClick, handleEditClick } = usePageModal(editCallback)
const modalRef = ref<InstanceType<typeof pageModal>>()
// function handleNewClick() {
//   modalRef.value?.setModelVisible()
// }
// TODO!!通过hooks有问题生效不了
function handleEditClick(itemData: any) {
  // 1.让modal显示出来
  modalRef.value?.setModelVisible(false, itemData)
  // 2.编辑的回调
  if (editCallback) editCallback(itemData)
}

// 获取菜单
const mainStore = useMainStore()
const { entireMenus } = storeToRefs(mainStore)

const otherInfo = ref({})
function handleElTreeCheck(data1: any, data2: any) {
  const menuList = [...data2.checkedKeys, ...data2.halfCheckedKeys]
  otherInfo.value = { menuList }
}

const treeRef = ref<InstanceType<typeof ElTree>>()
function editCallback(itemData: any) {
  nextTick(() => {
    const menuIds = mapMenuListToIds(itemData.menuList)
    treeRef.value?.setCheckedKeys(menuIds)
  })
}
</script>

<style lang="less" scoped></style>
